package com.richest.api.utils;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.servlet.http.HttpServletRequest;

import com.richest.util.StringUtil;

public class HttpUtil {
	public static String getIpAddress(HttpServletRequest request) {
		String ip = request.getHeader("X-Forwarded-For");
		if (StringUtil.isNotNullOrEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
			// 多次反向代理后会有多个ip值，第一个ip才是真实ip
			int index = ip.indexOf(",");
			if (index != -1) {
				return ip.substring(0, index);
			} else {
				return ip;
			}
		}
		ip = request.getHeader("X-Real-IP");
		if (StringUtil.isNotNullOrEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
			return ip;
		}
		return request.getRemoteAddr();
	}

	public static String post(String urlPost, String param, String method, String encoding) throws Exception {
		URL url = new URL(urlPost);
		HttpURLConnection http = (HttpURLConnection) url.openConnection();
		http.setDoOutput(true);
		http.setDoInput(true);
		http.setRequestMethod(method);
		http.setUseCaches(false);
		http.setConnectTimeout(10000);
		http.setReadTimeout(10000);
		http.setInstanceFollowRedirects(true);
		http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
		BufferedWriter out = new BufferedWriter(new OutputStreamWriter(http.getOutputStream(), encoding));
		out.write(param);
		out.flush();
		out.close();
		BufferedReader in = new BufferedReader(new InputStreamReader(http.getInputStream(), encoding));
		String line = null;
		StringBuilder sb = new StringBuilder();

		while ((line = in.readLine()) != null) {
			sb.append(line);
		}

		in.close();
		http.disconnect();
		return sb.toString();
	}
}
